﻿using System;
using System.Threading.Tasks;
using BookSourceVerification.common;
using Newtonsoft.Json.Linq;
using NLog;

namespace BookSourceVerification.handlers;

class DoubtHandler : IHandler<JObject>
{
    private readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public bool IsChecked(JObject node, HandlerResult result)
    {
        return true;
    }

    /// <summary>
    /// 添加存疑分组到书源中，让用户自行判断是否需要自行在阅读APP上对该节点进行验证
    /// </summary>
    /// <param name="node">单个书源</param>
    /// <param name="result">单个书源</param>
    /// <returns>url拿到了，返回true，表示可以进一步进行其他handler处理；
    /// url拿不到，返回false，中断后续handler处理，该node被抛弃</returns>
    public Task DoHandler(JObject node, HandlerResult result)
    {
        // 获取 url 用于测试
        try
        {
            var url = node.Property(Config.BOOK_SOURCE_URL)?.Value.ToString();
            var uri = new Uri(url);
            result.Success(url);
            return Task.CompletedTask;
        }
        catch (Exception e) when (e is ArgumentNullException or UriFormatException)
        {
            // 拿不到 url ， 那就添加特殊组，记住提醒用户后续自己处理
            return AddQuestionMark(node, result);
        }
        catch (Exception e)
        {
            _logger.Error(e);
            result.Fail();
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 给书源分组添加 “存疑” 分组，让用户自行决定去留
    /// </summary>
    /// <param name="node"></param>
    /// <param name="result"></param>
    /// <returns></returns>
    private static Task AddQuestionMark(JObject node, HandlerResult result)
    {
        var groupProperty = node.Property(Config.BOOK_SOURCE_GROUP);
        if (groupProperty is null)
        {
            result.Fail();
            return Task.CompletedTask;
        }

        groupProperty.Value = groupProperty.Value.ToString().Replace($",{Config.BOOK_SOURCE_GROUP_VALUE}", "");
        groupProperty.Value = new JValue($"{groupProperty.Value},{Config.BOOK_SOURCE_GROUP_VALUE}");
        result.FinalSuccess();
        return Task.CompletedTask;
    }

    public void AfterHandler()
    {
    }
}